package com.colin.log.mvc;

import com.alibaba.fastjson.JSONObject;
import com.colin.log.util.LogUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * mvc日志打印切面
 * 指定为111顺序
 */
@Aspect
@Order(111)
@Component
public class MvcLogAspect {

    @Pointcut("(@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.PutMapping) || @annotation(org.springframework.web.bind.annotation.PatchMapping) || @annotation(org.springframework.web.bind.annotation.DeleteMapping)) && (@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        
        //记录请求
        long beginTime = System.currentTimeMillis();
        LogUtil.printSelectiveLog("mvc param:{}", joinPoint.getArgs());
        long cost = 0;
        try {
            
            result = joinPoint.proceed();

            cost = System.currentTimeMillis() - beginTime;
            
        } catch (Exception e) {
            cost = System.currentTimeMillis() - beginTime;
            throw e;
        } finally {
            //记录响应
            LogUtil.info("mvc response:{}", JSONObject.toJSONString(result));
            LogUtil.info("mvc rt:{}", cost);
        }
        return result;
    }

}
